﻿''' <summary>
''' ダーティオブジェクトクリエイター
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class DirtyObjectCreater

    Private Sub New()
    End Sub

    ''' <summary>
    ''' 追加ダーティに変換します
    ''' </summary>
    ''' <param name="instance"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ToAddDirtyObjects(instance As Object) As List(Of DirtyObject)
        Dim results As New List(Of DirtyObject)

        If instance Is Nothing Then Return results

        Dim lst = DirtyObjectCreater.ToCollection(instance)

        '強制的に追加ダーティに変換
        For Each item In lst
            Dim ia As ItemEntityArchive = DirectCast(EntityArchiver.Create(item), ItemEntityArchive)
            Dim ret = ia.ToAddDirtyObjects(item)
            results.AddRange(ret)
        Next

        Return results
    End Function

    ''' <summary>
    ''' 削除ダーティに変換します
    ''' </summary>
    ''' <param name="instance"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ToDeleteDirtyObjects(instance As Object) As List(Of DirtyObject)
        Dim results As New List(Of DirtyObject)

        If instance Is Nothing Then Return results

        'アーカイブ化
        Dim ca As IEntityArchive = EntityArchiver.Create(instance)

        '強制的に削除ダーティに変換
        For Each ia As ItemEntityArchive In ca.Archives
            Dim ret = ia.ToDeleteDirtyObjects
            results.AddRange(ret)
        Next

        Return results
    End Function

    ''' <summary>
    ''' コレクションに変換します
    ''' </summary>
    ''' <param name="obj">変換対象オブジェクト</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function ToCollection(obj As Object) As ICollection
        '空配列をキャッシュ
        Static blank As ICollection = DirectCast(Enumerable.Empty(Of Object)(), ICollection)

        Dim c = TryCast(obj, ICollection)
        If c IsNot Nothing Then
            Return c
        End If

        If obj IsNot Nothing Then
            Return {obj}
        End If

        '空配列を返す
        Return blank
    End Function
End Class
